package com.example.star.view.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import com.example.star.R;
import com.example.star.api_service.ApiAddress;
import com.example.star.api_service.ApiShoppingCart;
import com.example.star.entity.Address;
import com.example.star.entity.ShoppingCart;
import com.example.star.retrofit.ApiClient;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddShopCartActivity extends AppCompatActivity {

    private ImageView productImageView;
    private TextView productNameTextView;
    private TextView productPriceTextView;
    private TextView quantityTextView;
    private TextView totalPriceTextView;
    private EditText shoppingAddressEditText;
    private Button decreaseButton;
    private Button increaseButton;
    private Button submitButton;
    private Spinner addressSpinner;
    private List<Address> addressList = new ArrayList<>();
    private ArrayAdapter<String> addressAdapter; // 修改为 String 类型的适配器

    private int quantity = 1;
    private double unitPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_shop_cart);

        // 初始化视图组件
        productImageView = findViewById(R.id.product_image_view);
        productNameTextView = findViewById(R.id.product_name_text_view);
        productPriceTextView = findViewById(R.id.product_price_text_view);
        quantityTextView = findViewById(R.id.quantity_text_view);
        totalPriceTextView = findViewById(R.id.total_price_text_view);
        shoppingAddressEditText = findViewById(R.id.shopping_address_edit_text);
        decreaseButton = findViewById(R.id.decrease_button);
        increaseButton = findViewById(R.id.increase_button);
        submitButton = findViewById(R.id.submit_button);
        addressSpinner = findViewById(R.id.address_spinner);

        // 获取传递过来的数据
        Intent intent = getIntent();
        String starName = intent.getStringExtra("starName");
        String perimeterTitle = intent.getStringExtra("perimeterTitle");
        String prices = intent.getStringExtra("prices");
        String imageResource = intent.getStringExtra("imageResource");
        String productType = intent.getStringExtra("productType");
        String freight = intent.getStringExtra("freight");
        String deliveryAddress = intent.getStringExtra("deliveryAddress");

        unitPrice = Double.parseDouble(prices);

        // 显示商品信息
        productNameTextView.setText(perimeterTitle);
        productPriceTextView.setText("单价: " + prices+"元");
        quantityTextView.setText(String.valueOf(quantity));
        totalPriceTextView.setText("" + calculateTotalPrice());

        // 加载商品图片
        if (imageResource != null) {
            try {
                int imageResId = getResources().getIdentifier(imageResource, "drawable", getPackageName());
                if (imageResId != 0) {
                    productImageView.setImageResource(imageResId);
                } else {
                    Glide.with(this)
                            .load(imageResource)
                            .placeholder(R.drawable.register)
                            .error(R.drawable.register)
                            .into(productImageView);
                }
            } catch (Exception e) {
                Glide.with(this)
                        .load(imageResource)
                        .placeholder(R.drawable.register)
                        .error(R.drawable.register)
                        .into(productImageView);
            }
        }

        // 增减商品数量按钮点击事件
        decreaseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (quantity > 1) {
                    quantity--;
                    quantityTextView.setText(String.valueOf(quantity));
                    totalPriceTextView.setText("" + calculateTotalPrice());
                }
            }
        });

        increaseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                quantity++;
                quantityTextView.setText(String.valueOf(quantity));
                totalPriceTextView.setText("" + calculateTotalPrice());
            }
        });

        // 从SharedPreferences中获取用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        String userName = sharedPreferences.getString("username", "");

        // 从服务器获取该用户名对应的收货地址列表
        loadAddresses(userName);

        // 提交按钮点击事件
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String totalPrice = totalPriceTextView.getText().toString().trim();

                String address;
                if (addressSpinner.getSelectedItemPosition() == 0) {
                    address = shoppingAddressEditText.getText().toString().trim();
                    if (address.isEmpty()) {
                        Toast.makeText(AddShopCartActivity.this, "请填写收货地址", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    address = addressAdapter.getItem(addressSpinner.getSelectedItemPosition()).toString();
                }

                Intent intent = getIntent();
                String userName = intent.getStringExtra("userName");
                String starName = intent.getStringExtra("starName");
                String perimeterTitle = intent.getStringExtra("perimeterTitle");
                String imageResource = intent.getStringExtra("imageResource");
                String productType = intent.getStringExtra("productType");
                String freight = intent.getStringExtra("freight");
                String deliveryAddress = intent.getStringExtra("deliveryAddress");

                ShoppingCart item = new ShoppingCart();
                item.setUserName(userName);
                item.setImageResource(imageResource);
                item.setStarName(starName);
                item.setTitle(perimeterTitle);
                item.setProductType(productType);
                item.setPrices((unitPrice));
                item.setFreight(freight);
                item.setDeliveryAddress(deliveryAddress);
                item.setShoppingAddress(address);
                item.setQuantity((quantity));
                item.setTotalPrice(Double.valueOf(totalPrice));


                addToShoppingCart(item);
            }
        });
    }

    private double calculateTotalPrice() {
        return unitPrice * quantity;
    }

    //获取地址
    private void loadAddresses(String userName) {
        ApiAddress apiAddress = ApiClient.getApiAddress();
        Call<List<Address>> call = apiAddress.getAddressByUserName(userName);
        call.enqueue(new Callback<List<Address>>() {
            @Override
            public void onResponse(Call<List<Address>> call, Response<List<Address>> response) {
                if (response.isSuccessful()) {
                    addressList = response.body();
                    List<String> addressDisplayList = new ArrayList<>();
                    addressDisplayList.add("填写新地址");
                    for (Address addr : addressList) {
                        addressDisplayList.add(addr.getAddress());
                    }

                    addressAdapter = new ArrayAdapter<>(AddShopCartActivity.this,
                            android.R.layout.simple_spinner_item, addressDisplayList);
                    addressAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    addressSpinner.setAdapter(addressAdapter);

                    addressSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            if (position == 0) {
                                shoppingAddressEditText.setVisibility(View.VISIBLE);
                            } else {
                                shoppingAddressEditText.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(AddShopCartActivity.this, "获取地址失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(AddShopCartActivity.this, "获取地址失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<List<Address>> call, Throwable t) {
                Toast.makeText(AddShopCartActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void addToShoppingCart(ShoppingCart shoppingCart) {
        ApiShoppingCart apiShoppingCart = ApiClient.getApiShoppingCart();
        Call<ShoppingCart> call = apiShoppingCart.saveShoppingCart(shoppingCart);
        call.enqueue(new Callback<ShoppingCart>() {
            @Override
            public void onResponse(Call<ShoppingCart> call, Response<ShoppingCart> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(AddShopCartActivity.this, "加入购物车成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    try {
                        String errorMessage = response.errorBody().string();
                        Toast.makeText(AddShopCartActivity.this, "加入购物车失败: " + errorMessage, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(AddShopCartActivity.this, "加入购物车失败: 未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<ShoppingCart> call, Throwable t) {
                Toast.makeText(AddShopCartActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}